package com.health.information.controller;

import java.util.List;

import com.health.common.constant.CacheConstants;
import com.health.common.utils.MinIOUtils;
import com.health.common.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.health.common.annotation.Log;
import com.health.common.core.controller.BaseController;
import com.health.common.core.domain.AjaxResult;
import com.health.common.enums.BusinessType;
import com.health.information.domain.ContentInformation;
import com.health.information.service.IContentInformationService;
import com.health.common.utils.poi.ExcelUtil;
import com.health.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 资讯Controller
 * 
 * @author moxxie
 * @date 2025-11-03
 */
@RestController
@RequestMapping("/information/information")
public class ContentInformationController extends BaseController
{
    @Autowired
    private IContentInformationService contentInformationService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MinIOUtils minIOUtils;


    /**
     * 查询资讯列表
     */
    // ContentInformationController.java
// 修改列表查询接口，允许用户访问
// @PreAuthorize("@ss.hasPermi('information:information:list')")  // 注释掉权限检查
    @GetMapping("/list")
    public TableDataInfo list(ContentInformation contentInformation)
    {
        startPage();
        // 修改这里：将状态从"0"改为"1"，表示只查询已发布的资讯
        contentInformation.setStatus("1"); // 1表示已发布
        List<ContentInformation> list = contentInformationService.selectContentInformationList(contentInformation);
        return getDataTable(list);
    }

    /**
     * 导出资讯列表
     */
    //@PreAuthorize("@ss.hasPermi('information:information:export')")
    @Log(title = "资讯", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContentInformation contentInformation)
    {
        List<ContentInformation> list = contentInformationService.selectContentInformationList(contentInformation);
        ExcelUtil<ContentInformation> util = new ExcelUtil<ContentInformation>(ContentInformation.class);
        util.exportExcel(response, list, "资讯数据");
    }

    /**
     * 获取资讯详细信息
     */
    //@PreAuthorize("@ss.hasPermi('information:information:query')")
    @GetMapping(value = "/{articleId}")
    public AjaxResult getInfo(@PathVariable("articleId") Long articleId)
    {
        return success(contentInformationService.selectContentInformationByArticleId(articleId));
    }

    /**
     * 新增资讯
     */
    //@PreAuthorize("@ss.hasPermi('information:information:add')")
    @Log(title = "资讯", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ContentInformation contentInformation)
    {
        redisTemplate.opsForSet().add(CacheConstants.TMP_VALID_FILE_SET, contentInformation.getCoverImage());
        return toAjax(contentInformationService.insertContentInformation(contentInformation));
    }


    /**
     * 上传图片
     */
    @PostMapping("/uploadImg")
    public AjaxResult uploadImg(@RequestParam("file") MultipartFile file) {
        redisTemplate.opsForSet().add(CacheConstants.TMP_VALID_FILE_SET,file);
        try {
            if (file.isEmpty()) {
                return error("上传文件不能为空");
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (!contentType.startsWith("image/")) {
                return error("只能上传图片文件");
            }

            // 验证文件大小 (5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                return error("图片大小不能超过5MB");
            }

            // 上传图片到MinIO
            String url = minIOUtils.uploadFile(file);

            // 将图片URL添加到临时文件集合（用于后续清理）
            redisTemplate.opsForSet().add(CacheConstants.TMP_VALID_FILE_SET, url);

            return success(url);
        } catch (Exception e) {
            logger.error("上传图片失败", e);
            return error("上传图片失败: " + e.getMessage());
        }
    }
    /**
     * 修改资讯
     */
    //@PreAuthorize("@ss.hasPermi('information:information:edit')")
    @Log(title = "资讯", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ContentInformation contentInformation)
    {
        return toAjax(contentInformationService.updateContentInformation(contentInformation));
    }

    /**
     * 删除资讯
     */
    //@PreAuthorize("@ss.hasPermi('information:information:remove')")
    @Log(title = "资讯", businessType = BusinessType.DELETE)
	@DeleteMapping("/{articleIds}")
    public AjaxResult remove(@PathVariable Long[] articleIds)
    {
        return toAjax(contentInformationService.deleteContentInformationByArticleIds(articleIds));
    }


}
